<template>
  <div>
    <MyTable :list="list">
      <!-- 具名插槽 -->
      <template #head>
        <th>#</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>
      <!-- ↓ 解构 ↓ -->
      <template #body="{ row }">
        <td>{{ row.id }}</td>
        <td>{{ row.goods_name }}</td>
        <td>{{ row.goods_price }}</td>
        <td>
          <input
            class="tag-input form-control"
            style="width: 100px"
            type="text"
            v-if="row.inputVisible"
            v-model="row.inputvalue"
            v-fff
            @blur="row.inputVisible = false"
            @keydown.esc="row.inputvalue = ''"
            @keydown.enter="addFn(row)"
          />
          <button
            v-else
            style="display: block"
            class="btn btn-primary btn-sm add-tag"
            @click="row.inputVisible = true"
          >
            +Tag
          </button>
          <span
            v-for="(item, index) in row.tags"
            :key="index"
            class="badge badge-warning"
            >{{ item }}</span
          >
        </td>
        <td>
          <button @click="delFn(row.id)" class="btn btn-danger btn-sm">
            删除
          </button>
        </td>
      </template>
    </MyTable>
  </div>
</template>

<script>
import MyTable from '../components/MyTable'

export default {
  components: {
    MyTable,
  },
  methods: {
    delFn(id) {
      this.list = this.list.filter((item) => item.id !== id) // 删除所选项
    },
    // ↓ 添加tag ↓
    addFn(row) {
      if (row.inputvalue.trim() === '') {
        return alert('输入为空')
      }
      row.tags.push(row.inputvalue) // 向row.tags中推送新增的tag
      row.inputvalue = '' // 将input变回空
    },
  },
  data() {
    return {
      list: [], // 所有数据
    }
  },
  // 创建时获取列表
  created() {
    this.$axios({
      url: '/api/goods',
    })
      .then((res) => {
        console.log(res)
        this.list = res.data.data // 将获取到的内容传递给list
      })
      .catch((err) => {
        console.log(err)
      })
  },
  // 自动获取焦点
  directives: {
    fff: {
      inserted(el) {
        el.focus()
      },
    },
  },
}
</script>
